﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Ports;
using System.Windows.Forms;
using System.Reflection;
using System.Collections;
using System.Runtime.InteropServices;

namespace GPSMTest
{
    public partial class GpsForm : Form
    {
        public GpsForm()
        {
            InitializeComponent();
        }

        public int TextHead = 0;
        protected const byte DLE = 0x10;
        protected const byte STX = 0x02;
        protected const byte ETX = 0x03;
        protected const int BUFF_MAX = 1024;
        public bool NotShift, HaveHead;
        public CRC MyCrc = new CRC();
        public byte[] ParseBuffer = new byte[1024];
        public bool FlagTestRun;//是否在模拟中
        public bool IsNowRec = false;

        public bool IsStopTest = false;
        public long StopLongitude = 0;
        public long StopLatitude = 0;

        protected const int BUFFER_MAX = 300;
        public int RecHead, RecTail;
        struct MYRecDataBuffer
        {
            public int reclength;
            public byte[] rectext;
        }
        MYRecDataBuffer[] RecBuffer = new MYRecDataBuffer[BUFFER_MAX];

        public bool InAutoTest = false;
        public int RecFrameCnt;//接收数据变颜色

        struct TDataTest
        {
            public long[] Latitude;
            public long[] Longitude;
            public int AllNumber;
            public int NowNumber;
        }
        TDataTest DataTest;
        TDataTest TwoDataTest;

        public int MAXDATATEST = 26000;

        public string RecFileName = "RecData.txt";

        [DllImport("user32.dll", CharSet = CharSet.Unicode)]
        public static extern IntPtr PostMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

        public enum MyMessage
        {
            Message1 = 0x0401,
            Message2 = 0x0402
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            String[] portList = SerialPort.GetPortNames();
            for (int i = 0; i < portList.Length; i++)
            {
                this.cmbSerialPort.Items.Add(portList[i]);
            }

            RecHead = 0;
            RecTail = 0;
            for (int i = 0; i < BUFFER_MAX; i++)
            {
                RecBuffer[i].reclength = 0;
                RecBuffer[i].rectext = new byte[1024];
            }
            DataTest.Latitude = new long[MAXDATATEST];
            DataTest.Longitude = new long[MAXDATATEST];
            TwoDataTest.Latitude = new long[100];
            TwoDataTest.Longitude = new long[100];

            ComboBoxTest.SelectedIndex = 0;
        }

        private void GpsForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (serialPort1.IsOpen)
            {
                serialPort1.Close();
            }
            Application.Exit();
        }

        private void btnOpenSerial_Click(object sender, EventArgs e)
        {
            if (btnOpenSerial.Text == "打 开")
            {
                if (cmbSerialPort.Text != "")
                {
                    serialPort1.PortName = cmbSerialPort.Text;
                    serialPort1.Open();
                    btnOpenSerial.Text = "关 闭";
                }
            }
            else
            {
                serialPort1.Close();
                btnOpenSerial.Text = "打 开";
            }
        }

        public void SendDataToGPS(byte ptype, byte pcommand, byte[] ppuredata, uint dataindex, uint datalen1)
        {
            uint i, tmplen, tmphead;
            ushort crc1;
            byte[] psadd1 = new byte[4];

            byte[] tmpdata = new byte[1024];
            tmpdata.Initialize();
            tmpdata[2] = 0x02;
            tmpdata[3] = 0x00;
            tmphead = 4;
            tmpdata[tmphead] = 0x06;
            tmphead++;
            tmpdata[tmphead] = 0x00;
            tmphead++;
            tmpdata[tmphead] = ptype;
            tmphead++;
            tmpdata[tmphead] = pcommand;
            tmphead++;
            if (datalen1 > 0)
            {
                for (i = 0; i < datalen1; i++)
                {
                    tmpdata[tmphead + i] = ppuredata[i + dataindex];
                }
            }
            tmplen = (uint)(tmphead + datalen1);
            tmpdata[0] = (byte)(tmplen / 256);
            tmpdata[1] = (byte)(tmplen % 256);
            crc1 = MyCrc.Proc_CRC(tmpdata, 0, (ushort)tmplen);
            tmpdata[tmplen] = (byte)(crc1 / 256);
            tmpdata[tmplen + 1] = (byte)(crc1 % 256);
            byte[] tmpdata1 = new byte[tmplen + 8];
            tmpdata1[0] = DLE;
            tmpdata1[1] = STX;
            for (i = 0; i < tmplen + 2; i++)
                tmpdata1[2 + i] = tmpdata[i];
            tmpdata1[tmplen + 4] = DLE;
            tmpdata1[tmplen + 5] = ETX;
            byte[] senddata1 = new byte[1024];
            int senddata1_len = 0;
            senddata1_len = Add0x10toArray(tmpdata1, (int)(tmplen + 6), senddata1);
            SendDataPort(senddata1, 0, senddata1_len);
        }

        private void SendDataPort(byte[] tmparray, int index, int length)
        {
            byte[] tmp1 = new byte[1];
            if (serialPort1.IsOpen)
            {
                serialPort1.Write(tmparray, index, length);
            }
        }

        private int Add0x10toArray(byte[] tmparray1, int len1, byte[] newarray1)
        {
            int i = 0, j = 0;
            byte[] addarray1 = new byte[1024];

            for (i = 0; i < len1 - 4; i++)
            {
                addarray1[i + j] = tmparray1[i + 2];
                if (tmparray1[i + 2] == 0x10)
                {
                    j++;
                    addarray1[i + j] = 0x10;
                }
            }
            j = i + j;
            for (i = 0; i < j; i++)
            {
                newarray1[i + 2] = addarray1[i];
            }
            newarray1[0] = 0x10;
            newarray1[1] = 0x02;
            newarray1[j + 2] = 0x10;
            newarray1[j + 3] = 0x03;
            i = j + 4;
            return i;
        }		

        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            ReadByte();
        }

        private void Parse_Serial_Data1(byte[] SBuf)
        {
            int j;
            int i = SBuf.Length;

            for (j = 0; j < i; j++)
            {
                switch (SBuf[j])
                {
                    case STX:
                        if ((TextHead > 0) && (ParseBuffer[TextHead - 1] == DLE) && NotShift)
                        {
                            HaveHead = true;
                            ParseBuffer[0] = DLE;
                            ParseBuffer[1] = STX;
                            TextHead = 2;
                        }
                        else
                        {
                            if (TextHead < BUFF_MAX)
                            {
                                if (TextHead < 0) TextHead = 0;
                                ParseBuffer[TextHead] = SBuf[j];
                                TextHead++;
                            }
                        }
                        break;
                    case ETX:
                        if ((TextHead > 0) && (ParseBuffer[TextHead - 1] == DLE) && NotShift)
                        {
                            if (TextHead < BUFF_MAX)
                            {
                                if (TextHead < 0) TextHead = 0;
                                ParseBuffer[TextHead] = SBuf[j];
                                TextHead++;
                            }
                            if (HaveHead)
                            {
                                Parse_Data((ushort)(TextHead));
                            }
                            HaveHead = false;
                            TextHead = 0;
                        }
                        else
                        {
                            if (TextHead < BUFF_MAX)
                            {
                                if (TextHead < 0) TextHead = 0;
                                ParseBuffer[TextHead] = SBuf[j];
                                TextHead++;
                            }
                        }
                        break;
                    case DLE:
                        if ((TextHead < 1) || ((TextHead >= 0) && (ParseBuffer[TextHead - 1] != DLE)) || (!NotShift))
                        {
                            if (TextHead < BUFF_MAX)
                            {
                                if (TextHead < 0) TextHead = 0;
                                ParseBuffer[TextHead] = SBuf[j];
                                NotShift = true;
                                TextHead++;
                            }
                        }
                        else
                        {
                            NotShift = false;
                        }
                        break;
                    default:
                        if (TextHead < BUFF_MAX)
                        {
                            if (TextHead < 0) TextHead = 0;
                            ParseBuffer[TextHead] = SBuf[j];
                            NotShift = true;
                            TextHead++;
                        }
                        else
                        {
                            TextHead = 0;
                        }
                        break;
                }
            }
        }

        private void Parse_Data(ushort datalength)
        {
            int i;
            byte[] databuffer = new byte[1024];

            ParseBuffer.CopyTo(databuffer, 0);
            if (datalength > 8)
            {
                RecBuffer[RecHead].reclength = (byte)datalength;
                for (i = 0; i < datalength; i++)
                {
                    RecBuffer[RecHead].rectext[i] = databuffer[i];
                }
                RecHead++;
                if (RecHead >= BUFFER_MAX)
                {
                    RecHead = 0;
                }
            }
        }

        private void ShowOneRecData()
        {
            string str1 = "";
            string strrec = "";
            byte sourceport, sourcelen, destport, destlen;
            byte commstyle, commcommand, tHead;
            int i, k, datalen;
            byte[] databuffer = new byte[1024];

            RecBuffer[RecTail].rectext.CopyTo(databuffer, 0);
            datalen = RecBuffer[RecTail].reclength;

            sourceport = databuffer[4];
            sourcelen = databuffer[5];
            tHead = 6;
            tHead += sourcelen;

            destport = databuffer[tHead];
            tHead++;
            destlen = databuffer[tHead];
            tHead++;
            tHead += destlen;

            commstyle = databuffer[tHead];
            tHead++;
            commcommand = databuffer[tHead];

            string s = "   ";
            k = 0;
            if (commcommand != 0xa2)
            {
                #region command raw data
                for (i = 0; i < datalen; i++)
                {
                    string s1 = string.Format("{0:X}H", databuffer[i]);
                    if (s1.Length == 2)
                        s1 = "0" + s1;
                    s += s1 + "  ";
                    k++;
                    if (k == 10)
                    {
                        str1 += s + "\r\n";
                        k = 0;
                        s = "   ";
                    }
                }
                #endregion
            }
            else
            {
                return;
            }
            str1 += s + "\r\n";
            if ((datalen == 164) && (databuffer[10] == 0x03) && (databuffer[11] == 0x01))
            {
                if (databuffer[12] == 0x41)
                {
                    #region 位置信息
                    char[] schar1 = new char[2];
                    schar1[0] = (char)0x20;
                    schar1[1] = '\0';
                    string sshow1 = Encoding_GetString(databuffer, 13, 8);
                    str1 += "线路区段名称：" + sshow1.Trim(schar1) + "    ";
                    str1 += "线路区段代码：" + (databuffer[21] + databuffer[22] * 256).ToString() + "\r\n";
                    sshow1 = Encoding_GetString(databuffer, 23, 21).Trim(schar1);

                    str1 += "区段名称：" + sshow1 + "    ";
                    strrec = Encoding_GetString(databuffer, 13, 8).Trim() + " " + sshow1.Trim() + " " + (databuffer[21] + databuffer[22] * 256).ToString() + " ";
                    str1 += "工作模式：" + databuffer[44].ToString() + "\r\n";
                    strrec += "模:" + databuffer[44].ToString() + " ";
                    if ((databuffer[45] != 0xff) || (databuffer[46] != 0xff))
                    {
                        sshow1 = MyCrc.BCDToHex(databuffer[45], 2).ToString() + MyCrc.BCDToHex(databuffer[46], 2).ToString("00");
                        str1 += "当前位置经度：" + sshow1 + "度";
                        strrec += "经:" + sshow1 + "度";
                        sshow1 = MyCrc.BCDToHex(databuffer[47], 2).ToString("00") + "." + MyCrc.BCDToHex(databuffer[48], 2).ToString("00")
                            + MyCrc.BCDToHex(databuffer[49], 2).ToString("00");
                        str1 += sshow1 + "分";
                        strrec += sshow1 + "分";
                        ulong lonnum1 = MyCrc.BCDToHex(databuffer[45], 2) * 100000000 + MyCrc.BCDToHex(databuffer[46], 2) * 1000000
                            + MyCrc.BCDToHex(databuffer[47], 2) * 10000 + MyCrc.BCDToHex(databuffer[48], 2) * 100 + MyCrc.BCDToHex(databuffer[49], 2);
                        lonnum1 = lonnum1 / 1000000 * 100000 + (lonnum1 % 1000000 / 6);
                        str1 += "    " + lonnum1.ToString() + "\r\n";
                        strrec += " " + lonnum1.ToString() + " ";

                        sshow1 = MyCrc.BCDToHex(databuffer[50], 2).ToString();
                        str1 += "当前位置纬度：" + sshow1 + "度";
                        strrec += "纬：" + sshow1 + "度";
                        sshow1 = MyCrc.BCDToHex(databuffer[51], 2).ToString("00") + "." + MyCrc.BCDToHex(databuffer[52], 2).ToString("00")
                            + MyCrc.BCDToHex(databuffer[53], 2).ToString("00");
                        str1 += sshow1 + "分";
                        strrec += sshow1 + "分";
                        ulong latnum1 = MyCrc.BCDToHex(databuffer[50], 2) * 1000000 + MyCrc.BCDToHex(databuffer[51], 2) * 10000
                            + MyCrc.BCDToHex(databuffer[52], 2) * 100 + MyCrc.BCDToHex(databuffer[53], 2);
                        latnum1 = latnum1 / 1000000 * 100000 + (latnum1 % 1000000 / 6);
                        str1 += "    " + latnum1.ToString() + "\r\n";
                        strrec += " " + latnum1.ToString() + " ";

                        //MyGpsHyLine.DealWithGPSLonAndLat(lonnum1, latnum1);//*****************
                        //if (HyGpsForm.IsShow)
                        //{
                        //    HyGpsForm.MyHyGpsForm.ShowHyGps(MyGpsHyLine.GpsNowInformation);
                        //    SetIsInSpecialGPSAreal(lonnum1, latnum1);
                        //}
                    }
                    str1 += "当前时间：" + MyCrc.BCDToHex(databuffer[54], 2).ToString() + "年" + MyCrc.BCDToHex(databuffer[55], 2).ToString()
                        + "月" + MyCrc.BCDToHex(databuffer[56], 2).ToString() + "日" + MyCrc.BCDToHex(databuffer[57], 2).ToString() + "时"
                        + MyCrc.BCDToHex(databuffer[58], 2).ToString() + "分" + MyCrc.BCDToHex(databuffer[59], 2).ToString() + "秒" + "\r\n";
                    sshow1 = Encoding_GetString(databuffer, 60, 8);
                    str1 += "调度电话号码：" + sshow1.Trim(schar1) + "\r\n";
                    //if (!HyGpsForm.IsShow)
                    {
                        for (i = 0; i < 4; i++)
                        {
                            sshow1 = Encoding_GetString(databuffer, 68 + i * 18, 8);
                            str1 += "车站" + (i + 1).ToString() + "名称：" + sshow1.Trim(schar1) + " ";
                            strrec += " 站" + (i + 1).ToString() + ":" + sshow1.Trim(schar1).Trim() + " ";
                            str1 += "代码：" + (databuffer[76 + i * 18] + databuffer[77 + i * 18] * 256).ToString() + " ";
                            //strrec += "Code："+(databuffer[76+i*18]+databuffer[77+i*18]*256).ToString()+ " ";
                            sshow1 = Encoding_GetString(databuffer, 78 + i * 18, 8);
                            str1 += "电话号码：" + sshow1.Trim(schar1);
                            strrec += "电话" + (i + 1).ToString() + ":" + sshow1.Trim(schar1);
                            str1 += "\r\n";
                        }
                    }
                    //else
                    //{
                    //    for (i = 0; i < 4; i++)
                    //    {
                    //        sshow1 = Encoding_GetString(databuffer, 68 + i * 18, 8);
                    //        str1 += "车站" + (i + 1).ToString() + "名称：" + sshow1.Trim(schar1) + " ";
                    //        strrec += " Station" + (i + 1).ToString() + ":" + MyGpsHyLine.GpsNowInformation.stationname[i] + " ";
                    //        str1 += "代码：" + (databuffer[76 + i * 18] + databuffer[77 + i * 18] * 256).ToString() + " ";
                    //        //strrec += "Code："+(databuffer[76+i*18]+databuffer[77+i*18]*256).ToString()+ " ";
                    //        sshow1 = Encoding_GetString(databuffer, 78 + i * 18, 8);
                    //        str1 += "电话号码：" + sshow1.Trim(schar1);
                    //        strrec += "Phone" + (i + 1).ToString() + ":" + MyGpsHyLine.GpsNowInformation.stationphone[i];
                    //        str1 += "\r\n";
                    //    }
                    //}
                    #endregion
                }
                else
                {
                    //
                }
            }
            else
            {
                strrec += str1;
                if ((commstyle == 0x02) && (commcommand == 0x01))
                {
                    #region
                    strrec += "进入线路选择区域";
                    strrec += DealWithLineData(databuffer, 10, datalen - 10);
                    SetPictureShow(true);
                    if (!InAutoTest)
                    {
                        ShowSetLineAuto(1);
                    }
                    #endregion
                }
                else if ((commstyle == 0x02) && (commcommand == 0x02))
                {
                    #region
                    strrec += "请确认线路：";
                    strrec += DealWithLineData(databuffer, 10, datalen - 10);
                    if (!InAutoTest)
                        ShowSetLineAuto(0);
                    #endregion
                }
                else if ((commstyle == 0x02) && (commcommand == 0x12))
                {
                    #region
                    strrec += "请选择线路：";
                    strrec += DealWithLineData(databuffer, 10, datalen - 10);
                    if (!InAutoTest)
                        ShowSetLineAuto(1);
                    #endregion
                }
                else if ((commstyle == 0x02) && (commcommand == 0x03))
                {
                    #region
                    strrec += "退出线路选择区域";
                    SetPictureShow(false);
                    #endregion
                }
            }
            switch (commcommand)
            {
                case 0xa1:
                    str1 += "GPS板已进入模拟状态！"; break;
                case 0xb2:
                    str1 += "GPS板忙碌中...."; break;
                case 0xa3:
                    str1 += "GPS板已退出模拟状态！"; break;
                case 0xa4:
                    switch (databuffer[tHead + 1])
                    {
                        case 0: break;
                        case 1:
                            int nyear = databuffer[tHead + 7];
                            int nmonth = databuffer[tHead + 6];
                            int nday = databuffer[tHead + 5];
                            int nhour = databuffer[tHead + 4];
                            int nminute = databuffer[tHead + 3];
                            int nsecond = databuffer[tHead + 2];
                            //TextBoxDBVersion.Text = nyear.ToString("00") + "年" + nmonth.ToString("00") + "月" + nday.ToString("00") + "日"
                            //    + nhour.ToString("00") + "时" + nminute.ToString("00") + "分" + nsecond.ToString("00") + "秒" + "\r\n";
                            TextBoxDBVersion.Text += Encoding_GetString(databuffer, tHead + 2, 17); break;
                        case 2: break;
                        case 3:
                            TextBoxSoftVersion.Text = Encoding_GetString(databuffer, tHead + 2, 9) + Encoding_GetString(databuffer, tHead + 11, 8); break;
                    }
                    break;
                case 0xa5:
                    str1 += "GPS板校时成功！"; break;
                case 0x00:
                    break;

                default:
                    str1 += "未知命令！"; break;
            }
            RecFrameCnt++;
            if ((RecFrameCnt & 0x01) > 0)
                MainBox.ForeColor = Color.DarkGreen;
            else
                MainBox.ForeColor = Color.Blue;
            MainBox.Text = str1;

            #region Save fileSaveStr
            string path_dir = Application.StartupPath + "\\RecData\\";
            if (!Directory.Exists(path_dir))
                Directory.CreateDirectory(path_dir);

            using (FileStream fs1 = new FileStream(Application.StartupPath + @"\RecData\" + RecFileName, FileMode.OpenOrCreate))
            {
                TextWriter w1 = new StreamWriter(fs1, Encoding.Default);
                fs1.Seek(0, SeekOrigin.End);
                w1.WriteLine(strrec + " :" + (DateTime.Now.Ticks % 1000000000 / 1000000).ToString());
                w1.Close();
                fs1.Close();
            }
            #endregion
        }

        public void ReadByte()
        {
            byte[] tmparray1 = new byte[1024];

            if (serialPort1.IsOpen)
            {
                int len1 = serialPort1.Read(tmparray1, 0, 1024);
                if (len1 > 0)
                {
                    byte[] tmparray2 = new byte[len1];
                    for (int i = 0; i < len1; i++)
                    {
                        tmparray2[i] = tmparray1[i];
                    }
                    Parse_Serial_Data1(tmparray2);
                }
            }
        }

        private void timer50_Tick(object sender, EventArgs e)
        {
            while (RecTail != RecHead)
            {
                ShowOneRecData();
                RecTail++;
                if (RecTail >= BUFFER_MAX)
                    RecTail = 0;
            }
            
        }

        private void Timer1_Tick(object sender, System.EventArgs e)
        {
            if (!IsStopTest)
            {
                if (TwoDataTest.NowNumber >= TwoDataTest.AllNumber)
                {
                    if (DataTest.NowNumber >= (DataTest.AllNumber - 1))
                    {
                        if (IsNowRec)
                        {
                            ButtonRecord.Text = "记 录";
                            IsNowRec = false;
                        }
                        Timer1.Enabled = false;
                        //if (InAutoTest)
                        //{
                        //    MyPostMessage(MyMessage.Message1, 1, 0);
                        //}
                    }

                    SetArrayOfTestData(DataTest.Longitude[DataTest.NowNumber], DataTest.Latitude[DataTest.NowNumber],
                        DataTest.Longitude[DataTest.NowNumber + 1], DataTest.Latitude[DataTest.NowNumber + 1]);
                    DataTest.NowNumber++;
                    TwoDataTest.NowNumber = 0;

                    LabelShowTestProcess.Text = "模拟状态：" + DataTest.AllNumber.ToString() + "：" + DataTest.NowNumber.ToString();
                }
                if ((TwoDataTest.Longitude[TwoDataTest.NowNumber] != 0) && (TwoDataTest.Latitude[TwoDataTest.NowNumber] != 0))
                {
                    SetGpsTXData(TwoDataTest.Longitude[TwoDataTest.NowNumber], TwoDataTest.Latitude[TwoDataTest.NowNumber]);
                }
                else
                {
                    SendVGpsData();
                }
                StopLongitude = TwoDataTest.Longitude[TwoDataTest.NowNumber];
                StopLatitude = TwoDataTest.Latitude[TwoDataTest.NowNumber];
                TwoDataTest.NowNumber++;
            }
            else
            {
                if (StopLongitude != 0)
                    SetGpsTXData(StopLongitude, StopLatitude);
                else
                    SendVGpsData();
            }
        }
        public string Encoding_GetString(byte[] tmpbyte, int index, int len)
        {
            string str1 = "";
            try
            {
                str1 = Encoding.Default.GetString(tmpbyte, index, len);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
            return str1;
        }

        public struct LINESTRUCT
        {
            public int mode;
            public string linename;
            public string disname;
        }
        public string String_Rec = "";
        public ArrayList LineArray = new ArrayList();

        public bool IsValidInArea = false;

        public string DealWithLineData(byte[] tmpbyte, int index, int len)
        {
            int num = len / 30;
            string str1 = "";
            LineArray.Clear();
            for (int i = 0; i < num; i++)
            {
                LINESTRUCT linedata1 = new LINESTRUCT();
                linedata1.mode = tmpbyte[index + i * 31];
                linedata1.linename = Encoding.Default.GetString(tmpbyte, index + i * 31 + 1, 8);
                linedata1.disname = Encoding.Default.GetString(tmpbyte, index + i * 31 + 9, 21);
                LineArray.Add(linedata1);

                str1 += linedata1.mode.ToString() + " " + linedata1.linename + " " + linedata1.disname + "\r\n";
            }
            //if (IsInSpeacialAreal)
            //{
            //    LINESTRUCT linedata1 = new LINESTRUCT();
            //    linedata1.mode = SpecialSetGpsAreal.mode;
            //    linedata1.linename = SpecialSetGpsAreal.linename;
            //    linedata1.disname = SpecialSetGpsAreal.disname;
            //    LineArray.Add(linedata1);

            //    str1 += linedata1.mode.ToString() + " " + linedata1.linename + " " + linedata1.disname + "\r\n";
            //}
            return str1;
        }

        public void SetPictureShow(bool flag1)
        {
            IsValidInArea = flag1;
            if (IsValidInArea)
            {
                LabelSelectRegion.Text = "选择区域：已进入";
            }
            else
            {
                LabelSelectRegion.Text = "选择区域：未进入";
            }
        }

        public void ShowSetLineAuto(int num)
        {
            if (LineArray.Count > 0)
            {
                AskLineForm f1 = new AskLineForm();
                if (num == 0)
                    f1.Text = "请确认线路：";
                else
                    f1.Text = "请选择线路：";
                f1.Owner = this;
                f1.Show();
            }
        }

        private void ButtonConnect_Click(object sender, EventArgs e)
        {
            byte[] tmparray1 = new byte[1];
            SendDataToGPS(0x02, 0xa1, tmparray1, 0, 0);
        }

        private void ButtonExit_Click(object sender, EventArgs e)
        {
            byte[] tmparray1 = new byte[1];
            SendDataToGPS(0x02, 0xa3, tmparray1, 0, 0);
        }

        private void ButtonDBVersion_Click(object sender, EventArgs e)
        {
            byte[] tmparray1 = new byte[1];
            tmparray1[0] = 0x01;
            SendDataToGPS(0x02, 0xa4, tmparray1, 0, 1);
            TextBoxDBVersion.Text = "";
        }

        private void ButtonSoftVersion_Click(object sender, EventArgs e)
        {
            byte[] tmparray1 = new byte[1];
            tmparray1[0] = 0x03;
            SendDataToGPS(0x02, 0xa4, tmparray1, 0, 1);
            TextBoxSoftVersion.Text = "";
        }

        private void ButtonSendTestData_Click(object sender, EventArgs e)
        {
            InAutoTest = false;
            RecFileName = DateTime.Now.ToString("yyyyMMddHHmm") + "RecData.txt";
            ReadTestData(true);
        }

        private void ButtonFanSend_Click(object sender, EventArgs e)
        {
            InAutoTest = false;
            RecFileName = DateTime.Now.ToString("yyyyMMddHHmm") + "RecData.txt";
            ReadTestData(false);
        }

        private void ButtonRecord_Click(object sender, EventArgs e)
        {
            IsNowRec = !IsNowRec;
            if (IsNowRec)
                ButtonRecord.Text = "停 记";
            else
                ButtonRecord.Text = "记 录";
        }

        private void ButtonStopSend_Click(object sender, EventArgs e)
        {
            FlagTestRun = true;
            Timer1.Enabled = false;
        }

        private void ButtonStopCar_Click(object sender, EventArgs e)
        {
            if (IsStopTest)
            {
                IsStopTest = false;
                ButtonStopCar.Text = "停 车";
            }
            else
            {
                IsStopTest = true;
                ButtonStopCar.Text = "开 车";
            }
        }

        private void ButtonFindRegion_Click(object sender, EventArgs e)
        {
            //查询附近线路
            byte[] tmparray = new byte[100];
            SendDataToGPS(0x03, 0x4F, tmparray, 0, 0);
        }


        private void ComboBoxTest_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (ComboBoxTest.SelectedIndex)
            {
                case 0:
                    Timer1.Interval = 1500;
                    break;
                case 1:
                    Timer1.Interval = 800;
                    break;
                case 2:
                    Timer1.Interval = 300;
                    break;
                case 3:
                    Timer1.Interval = 150;
                    break;
            }
        }


        public void ReadTestData(bool isforward)
        {
            OpenFileDialog openf1 = new OpenFileDialog();
            openf1.Filter = "文本文件(*.txt)|*.txt";
            openf1.Title = "请选择模拟数据文件：";
            openf1.InitialDirectory = Application.StartupPath + "\\模拟数据";
            if (openf1.ShowDialog() == DialogResult.OK)
            {
                using (TextReader fs = File.OpenText(openf1.FileName))
                {
                    string filestr11 = Path.GetFileNameWithoutExtension(openf1.FileName);
                    if (isforward)
                    {
                        RecFileName = DateTime.Now.ToString("yyyyMMddHHmm") + "Rec" + filestr11 + ".txt";
                    }
                    else
                    {
                        RecFileName = DateTime.Now.ToString("yyyyMMddHHmm") + "FRec" + filestr11 + ".txt";
                    }

                    int i = 0, num = 0;
                    string str1 = "";

                    str1 = fs.ReadLine();
                    DataTest.AllNumber = Int32.Parse(str1);
                    DataTest.NowNumber = 0;
                    str1 = fs.ReadLine();
                    TwoDataTest.AllNumber = Int32.Parse(str1);
                    TwoDataTest.NowNumber = TwoDataTest.AllNumber;
                    while (true)
                    {
                        str1 = fs.ReadLine();
                        num++;
                        if ((str1 == null) || (num > MAXDATATEST))
                            break;
                        if (str1.Length > 30)
                        {
                            if (isforward)
                            {
                                DataTest.Longitude[i] = Int64.Parse(str1.Substring(str1.IndexOf("Lo(") + 3, 8));
                                DataTest.Latitude[i] = Int64.Parse(str1.Substring(str1.IndexOf("La(") + 3, 7));
                            }
                            else
                            {
                                DataTest.Longitude[DataTest.AllNumber - i - 1] = Int64.Parse(str1.Substring(str1.IndexOf("Lo(") + 3, 8));
                                DataTest.Latitude[DataTest.AllNumber - i - 1] = Int64.Parse(str1.Substring(str1.IndexOf("La(") + 3, 7));
                            }
                            if (++i >= DataTest.AllNumber)
                                break;
                        }
                    }
                    LabelShowTestProcess.Text = "模拟状态：" + DataTest.AllNumber.ToString() + "：" + DataTest.NowNumber.ToString();
                    Timer1.Enabled = true;
                    FlagTestRun = false;
                    fs.Close();
                }
            }
        }

        public void SendVGpsData()
        {
            byte[] tmpbyte = new byte[100];
            string str1 = "$GPRMC,000225.027,V,2232.9535,N,11405.2331,E,0.00,0.00,060180,,,N*70";
            int i = Encoding.Default.GetBytes(str1, 0, str1.Length, tmpbyte, 0);
            tmpbyte[i] = 0x0d;
            tmpbyte[i] = 0x0a;
            SendDataToGPS(0x02, 0xa2, tmpbyte, 0, (uint)(i + 2));
        }
        public void SetGpsTXData(long longitude, long latitude)
        {
            int i, t;
            string s = "$GPRMC,";
            byte d, m, m1, m2;
            DateTime st = DateTime.UtcNow;
            byte[] tmpbyte = new byte[100];

            longitude = longitude * 6;
            latitude = latitude * 6;
            i = Encoding.Default.GetBytes(s, 0, s.Length, tmpbyte, 0);
            t = (int)(MyCrc.HexToBCD((ulong)st.Hour, 2) & 0xff);
            tmpbyte[7] = (byte)((t / 16) + 0x30);
            tmpbyte[8] = (byte)((t & 0x0f) + 0x30);
            t = (int)(MyCrc.HexToBCD((ulong)st.Minute, 2) & 0xff);
            tmpbyte[9] = (byte)((t / 16) + 0x30);
            tmpbyte[10] = (byte)((t & 0x0f) + 0x30);
            t = (int)(MyCrc.HexToBCD((ulong)st.Second, 2) & 0xff);
            tmpbyte[11] = (byte)((t / 16) + 0x30);
            tmpbyte[12] = (byte)((t & 0x0f) + 0x30);
            tmpbyte[13] = (byte)('.');
            t = (int)(MyCrc.HexToBCD((ulong)st.Millisecond, 2) & 0xff);
            tmpbyte[14] = (byte)((t / 16) + 0x30);
            tmpbyte[15] = (byte)((t & 0x0f) + 0x30);
            tmpbyte[16] = (byte)(',');
            tmpbyte[17] = (byte)('A');
            tmpbyte[18] = (byte)(',');

            d = (byte)(latitude / 600000);
            latitude = latitude % 600000;
            m = (byte)(latitude / 10000);
            latitude = latitude % 10000;
            m1 = (byte)(latitude / 100);
            m2 = (byte)(latitude % 100);
            tmpbyte[19] = (byte)((d / 10) + 0x30);
            tmpbyte[20] = (byte)((d % 10) + 0x30);
            tmpbyte[21] = (byte)((m / 10) + 0x30);
            tmpbyte[22] = (byte)((m % 10) + 0x30);
            tmpbyte[23] = (byte)('.');
            tmpbyte[24] = (byte)((m1 / 10) + 0x30);
            tmpbyte[25] = (byte)((m1 % 10) + 0x30);
            tmpbyte[26] = (byte)((m2 / 10) + 0x30);
            tmpbyte[27] = (byte)((m2 % 10) + 0x30);
            tmpbyte[28] = (byte)(',');
            tmpbyte[29] = (byte)('N');
            tmpbyte[30] = (byte)(',');

            d = (byte)(longitude / 600000);
            longitude = longitude % 600000;
            m = (byte)(longitude / 10000);
            longitude = longitude % 10000;
            m1 = (byte)(longitude / 100);
            m2 = (byte)(longitude % 100);
            tmpbyte[31] = (byte)((d / 100) + 0x30);
            d = (byte)(d % 100);
            tmpbyte[32] = (byte)((d / 10) + 0x30);
            tmpbyte[33] = (byte)((d % 10) + 0x30);
            tmpbyte[34] = (byte)((m / 10) + 0x30);
            tmpbyte[35] = (byte)((m % 10) + 0x30);
            tmpbyte[36] = (byte)('.');
            tmpbyte[37] = (byte)((m1 / 10) + 0x30);
            tmpbyte[38] = (byte)((m1 % 10) + 0x30);
            tmpbyte[39] = (byte)((m2 / 10) + 0x30);
            tmpbyte[40] = (byte)((m2 % 10) + 0x30);
            tmpbyte[41] = (byte)(',');
            tmpbyte[42] = (byte)('E');
            tmpbyte[43] = (byte)(',');
            //<0.0>~<1851.8>,
            tmpbyte[44] = (byte)('1');
            tmpbyte[45] = (byte)('0');
            tmpbyte[46] = (byte)('0');
            tmpbyte[47] = (byte)('0');
            tmpbyte[48] = (byte)('.');
            tmpbyte[49] = (byte)('5');
            tmpbyte[50] = (byte)(',');
            //<0.0>~<359.9>,
            tmpbyte[51] = (byte)('1');
            tmpbyte[52] = (byte)('2');
            tmpbyte[53] = (byte)('5');
            tmpbyte[54] = (byte)('.');
            tmpbyte[55] = (byte)('1');
            tmpbyte[56] = (byte)(',');

            t = (int)(MyCrc.HexToBCD((ulong)st.Day, 2) & 0xff);
            tmpbyte[57] = (byte)((t / 16) + 0x30);
            tmpbyte[58] = (byte)((t & 0x0f) + 0x30);
            t = (int)(MyCrc.HexToBCD((ulong)st.Month, 2) & 0xff);
            tmpbyte[59] = (byte)((t / 16) + 0x30);
            tmpbyte[60] = (byte)((t & 0x0f) + 0x30);
            t = (int)(MyCrc.HexToBCD((ulong)st.Year, 2) & 0xff);
            tmpbyte[61] = (byte)((t / 16) + 0x30);
            tmpbyte[62] = (byte)((t & 0x0f) + 0x30);
            tmpbyte[63] = (byte)(',');
            tmpbyte[64] = (byte)('9');
            tmpbyte[65] = (byte)('0');
            tmpbyte[66] = (byte)('.');
            tmpbyte[67] = (byte)('6');
            tmpbyte[68] = (byte)(',');
            tmpbyte[69] = (byte)('E');
            tmpbyte[70] = (byte)(',');
            d = tmpbyte[1];
            for (i = 2; i < 71; i++)
                d = (byte)(d ^ tmpbyte[i]);
            tmpbyte[71] = (byte)('*');
            m = (byte)(d / 16);
            if (m > 9)
                tmpbyte[72] = (byte)(m + 0x37);
            else
                tmpbyte[72] = (byte)(m + 0x30);
            m = (byte)(d & 0x0f);
            if (m > 9)
                tmpbyte[73] = (byte)(m + 0x37);
            else
                tmpbyte[73] = (byte)(m + 0x30);
            tmpbyte[74] = 0x0d;
            tmpbyte[75] = 0x0a;

            SendDataToGPS(0x02, 0xa2, tmpbyte, 0, 76);
        }

        public void MyPostMessage(MyMessage nummes, int num1, int num2)
        {
            PostMessage(this.Handle, (int)nummes, new IntPtr(num1), new IntPtr(num2));
        }

        protected override void WndProc(ref Message msg)
        {
            switch (msg.Msg)
            {
                case (int)MyMessage.Message1: 
                   // DealWithAutoTest((int)msg.WParam); 
                    break;
            }

            base.WndProc(ref msg);
        }

        public void SetArrayOfTestData(long long1, long late1, long long2, long late2)
        {
            int i, tmpnum1;
            if ((long1 == 0) || (long2 == 0))
            {
                for (i = 0; i <= TwoDataTest.AllNumber; i++)
                {
                    TwoDataTest.Longitude[i] = 0;
                    TwoDataTest.Latitude[i] = 0;
                }
            }
            else
            {
                if (long1 == long2)
                {
                    for (i = 0; i <= TwoDataTest.AllNumber; i++)
                        TwoDataTest.Longitude[i] = long1;
                }
                else
                {
                    TwoDataTest.Longitude[0] = long1;
                    TwoDataTest.Longitude[TwoDataTest.AllNumber] = long2;

                    tmpnum1 = (int)(Math.Abs(TwoDataTest.Longitude[0] - TwoDataTest.Longitude[TwoDataTest.AllNumber]) / TwoDataTest.AllNumber);

                    for (i = 1; i < TwoDataTest.AllNumber; i++)
                    {
                        if (long1 > long2)
                            TwoDataTest.Longitude[i] = TwoDataTest.Longitude[0] - tmpnum1 * i;
                        else
                            TwoDataTest.Longitude[i] = TwoDataTest.Longitude[0] + tmpnum1 * i;
                    }
                }
                if (late1 == late2)
                {
                    for (i = 0; i <= TwoDataTest.AllNumber; i++)
                        TwoDataTest.Latitude[i] = late1;
                }
                else
                {
                    TwoDataTest.Latitude[0] = late1;
                    TwoDataTest.Latitude[TwoDataTest.AllNumber] = late2;

                    tmpnum1 = (int)(Math.Abs(TwoDataTest.Latitude[0] - TwoDataTest.Latitude[TwoDataTest.AllNumber]) / TwoDataTest.AllNumber);
                    for (i = 1; i < TwoDataTest.AllNumber; i++)
                    {
                        if (late1 > late2)
                            TwoDataTest.Latitude[i] = TwoDataTest.Latitude[0] - tmpnum1 * i;
                        else
                            TwoDataTest.Latitude[i] = TwoDataTest.Latitude[0] + tmpnum1 * i;
                    }
                }
            }
        }

       
       

    }
}
